/**
 移动页面Controller
 @class logs
 @author :laiwp
 @date:  :2016-07-01
 @version : 0.1.0
 @constructor : 0.1.0
 */
var config = require('../settings');
var tools = require('../tools.js');
var https = require('https');
var async = require('async');
var md5 = require('md5');
var moment = require('moment');

var ObjValues = require ('object.values');
var dbDao = require('../models/dbBase.js');


module.exports = {
    mapping: {
        _sport_member: {
            'url': '/sport/member',
            'method': 'get',
            'description': '个人中心',
            'auth': false
        },
        _sport_member_orders: {
            'url': '/sport/member/orders',
            'method': 'get',
            'description': '我的订单',
            'auth': false
        },
        _sport_member_orderinfo: {
            'url': '/sport/member/orderinfo',
            'method': 'get',
            'description': '订单详情',
            'auth': false
        },
        _sport_member_cancelorder: {
            'url': '/sport/member/cancelorder',
            'method': 'post',
            'description': '订单取消',
            'auth': false
        },

    },

    //个人中心
    _sport_member: function (req, res) {
        var wxopenid = req.query.wxopenid;
            if (!wxopenid) {

                    res.send({result:'error',message:'无效的openid'});
            } else {
              var sql = "select * from members where wxopenId='" + wxopenid + "'";
              dbDao.find(sql, function (err, result2) {
                  if(err){
                      res.send({result:'error',message:'查询用户失败'});
                  }else{
                      if (result2.length > 0) {
                          console.log("老微信一键登陆用户", result2[0]);

                          res.send({result:'success',
                              data: result2[0]
                          });
                      }else{
                          res.send({result:'error',message:'没有查询到用户'});
                      }
                  }
              });
            }
    },

    //我的订单
    _sport_member_orders: function (req, res) {

        var wxopenId = req.query.wxopenid;

        /**
         * 资源分组算法,将资源按照场地分开
         * @param arr
         * @returns {{}}
         */
        function part(arr) {
            var newArr;
            if (arr.length <= 0) {
                return
            }
            var a = {};

            for (var i = 0; i < arr.length; i++) {
                if (a[arr[i].name]) {
                    a[arr[i].name].push(arr[i]);

                } else {
                    a[arr[i].name] = [];
                    a[arr[i].name].push(arr[i]);
                }
            }
            return a;

        }

        /**
         * 组合算法,将每个场地的资源按照时间整合合并;
         * @param arr
         * @returns {Array}
         */
        function bijiao(x, y) {
            return x.beginTime - y.beginTime;
        }

        function group(arr) {
            arr.sort(bijiao);
            var newObj = [];
            var t = 0;
            newObj[t] = {beginTime: arr[0].beginTime, date: arr[0].date}
            for (var i = 0; i < arr.length - 1; i++) {
                if (arr[i + 1]) {
                    if (arr[i].endTime == arr[i + 1].beginTime) {
                        newObj[t]['endTime'] = arr[i + 1].endTime;
                    } else {
                        newObj[++t] = {beginTime: arr[i + 1].beginTime, date: arr[0].date}
                    }
                }
            }
            newObj[t]["endTime"] = arr[arr.length - 1].endTime;
            return newObj;
        }

        function bigGroup(arr) {
            var bigarr = {};
            for (var i in arr) {
                bigarr[i] = group(arr[i]);
            }
            return bigarr;
        }

        var sql = "select * from orders where wxopenId=? and orderStatus=?";
        var sql2 = "select * from orders where wxopenId=?";
        var sql3 = "select * from OrderItem where orderId=?";
        var sql4 = "select * from GymResource where id=?";

        var params1 = [wxopenId, '0'];  //待支付
        var params2 = [wxopenId, '1'];  //已支付
        console.log(params2);

        var orderResult = [];
        var arrResult = [];
        var arrOrderResouce = [];
        dbDao.querys(sql2, [wxopenId], function (err, result3) {
            console.log("订单result3.length", result3.datas.length);

            orderResult = result3.datas;
            async.each(result3.datas, function (item, callback) {
                dbDao.querys( sql3, [item.id], function (err, result4) {

                    item['clmItemId'] = result4.datas.map(function (ele, index) {
                        return ele.sourceId;
                    });
                    console.log(item['clmItemId']);
                    arrResult.push(item);
                    callback(null);

                });
            }, function (err) {
                console.log(arrResult);
                /**
                 *  循环便利每一条订单;
                 */
                async.each(arrResult, function (item, callback1) {
                    /**
                     * 循环便利订单里每一条资源;
                     */
                    item['clmresouce'] = []
                    async.each(item.clmItemId, function (i, callback) {
                        console.log(i);
                        dbDao.querys( sql4, i, function (err, result) {
                            console.log(result);
                            item['clmresouce'].push(result.datas[0]);
                            callback();
                        })
                    }, function (err) {
                        arrOrderResouce.push(item);
                        callback1()
                    })
                }, function (err) {
                    var arrOrderResouce2 = arrOrderResouce.map(function (ele, index) {
                        ele['part'] = part(ele.clmresouce);
                        return ele;
                    });
                    var arrOrderResouce3 = arrOrderResouce2.map(function (ele, index) {
                        ele['group'] = bigGroup(ele.part);
                        return ele;
                    });
                    arrOrderResouce3 = arrOrderResouce3.map(function (ele, index) {
                        ele['changDi'] = Object.keys(ele.group);
                        ele['shijian'] = ObjValues(ele.group)[0][0].date;
                        var t = ObjValues(ele.group).map(function (ele) {
                            return ele[0].beginTime;
                        }).sort()[0];
                        ele['startshijian'] = moment(t, "YYYYMMDDHHmmsss").format("MM/DD HH:mm");
                        return ele;
                    })
                    var data1 = arrOrderResouce3.filter(function (ele, index) {
                        return ele.orderStatus == "0";
                    });
                    var data2 = arrOrderResouce3.filter(function (ele, index) {
                        return ele.orderStatus == "1";
                    });
                    //res.json(arrOrderResouce3);
                    res.send( {
                        locals: {
                            title: config.title,
                            payingOrder: data1,
                            paiedOrder: data2,
                            allOrder: arrOrderResouce3
                        }
                    })
                })
            })

        })

    },

    //取消订单
    _sport_member_cancelorder: function (req, res) {

        var orderNo = req.body.orderNo;
        if(!orderNo){

            res.send({result:'error',message:'无效的订单号'});
        }else{
            var sql = "update orders set orderStatus=? where id=?";
            var params = ['2', orderNo];
            dbDao.querys(sql, params, function (err, result) {
                if(err){

                    res.send({result:'error',message:'取消订单失败'});
                }else{
                    res.send({result:'success',data:{}});
                }
            });
        }


    },
    //订单详情
    _sport_member_orderinfo: function (req, res) {
        /**
         * 资源分组算法,将资源按照场地分开
         * @param arr
         * @returns {{}}
         */
        function part(arr) {
            var newArr;
            if (arr.length <= 0) {
                return
            }
            var a = {};

            for (var i = 0; i < arr.length; i++) {
                if (a[arr[i].name]) {
                    a[arr[i].name].push(arr[i]);

                } else {
                    a[arr[i].name] = [];
                    a[arr[i].name].push(arr[i]);
                }
            }
            return a;

        }

        /**
         * 组合算法,将每个场地的资源按照时间整合合并;
         * @param arr
         * @returns {Array}
         */
        function bijiao(x, y) {
            return x.beginTime - y.beginTime;
        }

        function group(arr) {
            arr.sort(bijiao);
            var newObj = [];
            var t = 0;
            newObj[t] = {beginTime: arr[0].beginTime, date: arr[0].date, price: arr[0].price}
            for (var i = 0; i < arr.length - 1; i++) {
                if (arr[i + 1]) {
                    if (arr[i].endTime == arr[i + 1].beginTime) {
                        newObj[t]['endTime'] = arr[i + 1].endTime;
                    } else {
                        newObj[++t] = {beginTime: arr[i + 1].beginTime, date: arr[0].date, price: arr[0].price}
                    }
                }
            }
            newObj[t]["endTime"] = arr[arr.length - 1].endTime;
            return newObj;
        }

        function bigGroup(arr) {
            var bigarr = {};
            for (var i in arr) {
                bigarr[i] = group(arr[i]);
            }
            return bigarr;
        }
        function objValues(obj){
            var keys = Object.keys[obj];

        }
        /**
         * 拼接对象
         * @param arr
         * @returns {Array}
         */
        function pinjie(obj) {
            var arr = [];
            var t = -1
            for (i in obj) {
                for (var j = 0; j < obj[i].length; j++) {
                    arr[++t] = {};
                    arr[t]["name"] = i;
                    Object.assign(arr[t], obj[i][j]);
                }

            }
            arr.sort(function (x, y) {
                return parseInt(x.name) - parseInt(y.name);
            });
            var newArr = arr.map(function (ele, index) {
                ele["zongjia"] = (ele.endTime - ele.beginTime) / 10000 * ele.price;
                ele["jiange"] = moment(ele.beginTime, "YYYYMMDDHHmmsss").format("HH:mm") + "-" + moment(ele.endTime, "YYYYMMDDHHmmsss").format("HH:mm");
                return ele;
            })
            return newArr;
        }

        var orderNo = req.param('orderNo');
        if(!orderNo){
            res.send(
                {result:'error',data: {
                }
                });
        }else{
            //查询OrderItem
            var sql1 = "select * from OrderItem where orderId=?";
            //查询资源
            var sql2 = "select * from GymResource where id=?";
            //查询场馆具体名称
            var sql3 = "select * from GymFields where id=?";
            var arrResult;
            var arrResult1 = [];
            var ziyuan = [];
            dbDao.findById( ["orders", "id", orderNo], function (err, result) {
                dbDao.querys(sql1, [result.id], function (err, result1) {
                    //res.json(result1.datas);
                    if(err){
                        res.send({result:'error',message:'查询订单失败'});
                    }
                    arrResult = result1;
                    async.each(arrResult.datas, function (item, callback1) {

                        dbDao.querys( sql2, [item.sourceId], function (err, result1) {
                            console.log(result1.datas);
                            ziyuan.push(result1.datas[0]);
                            callback1();
                        })

                    }, function (err) {

                        dbDao.querys( sql3, [ziyuan[0].gymFieldId], function (err, result2) {
                            if(err){

                                res.send({result:'error',message:'查询订单失败'});
                            }else{
                                var t = part(ziyuan);
                                console.log('---t:',t);
                                var s = bigGroup(t);
                                console.log('---',s);
                                var FiledName = result2.datas[0].name;
                                var starttime = ObjValues(s)[0][0].date;
                                var starttime2 = moment(starttime, "YYYYMMDD").format("YYYY-MM-DD");
                                var obj = {
                                    FiledName: FiledName,
                                    starttime: starttime2,
                                    details: pinjie(s)
                                }
                                Object.assign(obj, result);
                                res.send( {result:'success',
                                    data: obj
                                });
                            }

                        });
                    })
                })
            });
        }

    },
}
